(function() {
    const keys = document.querySelectorAll('.key');

    const numIndicator = document.getElementById('numlock'),
          capsIndicator = document.getElementById('capslock'),
          scrollIndicator = document.getElementById('scrolllock');

    const updateIndicators = e => {
        const num = e.getModifierState('NumLock'),
              caps = e.getModifierState('CapsLock'),
              scroll = e.getModifierState('ScrollLock');

        num ? numIndicator.classList.add('active') : numIndicator.classList.remove('active');
        caps ? capsIndicator.classList.add('active') : capsIndicator.classList.remove('active');
        scroll ? scrollIndicator.classList.add('active') : scrollIndicator.classList.remove('active');
    };

    window.addEventListener('keydown', e => {
        e.preventDefault();

        for(let key of keys) if(key.getAttribute('data-key').split(' ').includes(e.code)) key.classList.add('pressed');
    });

    window.addEventListener('keyup', e => {
        e.preventDefault();

        for(let key of keys) {
            const keyCodes = key.getAttribute('data-key').split(' ');

            if(keyCodes.includes(e.code)) key.classList.remove('pressed');

            if(keyCodes.includes('PrintScreen') && e.code === 'PrintScreen') {
                key.classList.add('pressed');

                setTimeout(() => {
                    key.classList.remove('pressed');
                }, 200);
            }
        };

        updateIndicators(e);
    });

    window.addEventListener('focus', e => {
        for(let key of keys) key.classList.remove('pressed');
    });
})();